# 利用OpenCV对本地car.avi视频分别进行霍夫直线检测和边缘检测题目要求：
# ①　导入相关头文件
import cv2 as cv
import numpy as np

# ②　打开摄像头或视频
path = 'data/lane.avi'
# path = 'data/vipunmarkedroad.avi'
cap = cv.VideoCapture(path)
np.random.seed(1)


def rand_color():
    return (
        np.random.randint(0, 256),
        np.random.randint(0, 256),
        np.random.randint(0, 256),
    )


INTERV = 30
frame_id = 0
while True:
    # ③　对读入帧转灰度
    ret, img = cap.read()
    if not ret:
        print('Video over.')
        break
    H, W = img.shape[:2]

    # ④　对读入帧转二值化
    gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
    ret, bin = cv.threshold(gray, 0, 255, cv.THRESH_OTSU + cv.THRESH_BINARY)

    # ⑦　选择一个边缘算子对视频进行边缘检测
    canny = cv.Canny(bin, 100, 200)

    # ⑤　进行霍夫直线检测
    lines = cv.HoughLinesP(canny, 1, np.pi/180, 50, minLineLength=50, maxLineGap=50)

    # ⑥　画出检测后的直线
    bg = np.zeros_like(img)
    for row in lines:
        for x1, y1, x2, y2 in row:
            cv.line(bg, (x1, y1), (x2, y2), rand_color())

    # ⑨　在视频上面左上角显示视频的帧率fps
    cv.putText(bg, f'FPS: {1000//INTERV:.2f}', (0, 20), cv.FONT_HERSHEY_PLAIN, 1., (0, 255, 0))

    # ⑩　在视频上显示视频的总帧数
    frame_id += 1
    cv.putText(bg, f'FRM: {frame_id}', (W - 180, 20), cv.FONT_HERSHEY_PLAIN, 1., (0, 255, 0))

    # ⑧　显示处理后的视频
    cv.imshow('video', bg)

    # 11　每帧处理完后加入30ms延时
    k = cv.waitKey(INTERV) & 0xFF
    if 27 == k:
        print('User cancelled.')
        break

cap.release()
cv.destroyAllWindows()
